package com.yy.device.core.job;

import com.alibaba.fastjson.JSON;
import com.yy.device.boot.DeviceServer;
import com.yy.device.boot.protocol.TaskMessage;
import com.yy.device.core.entity.Task;
import com.yy.device.core.service.TaskService;
import com.yy.device.enums.DeviceDataEnum;
import com.yy.device.enums.DeviceFunctionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 命令作业处理程序
 *
 * @author sunzhiqiang
 * @date 2021/12/14 15:54:18
 */
@Slf4j
@Component
public class CommandJobTask {

    @Resource
    private DeviceServer deviceServer;
    @Resource
    private TaskService taskService;

    @Scheduled(fixedRateString = "3000")
    public void execute() {
        List<Task> entities = taskService.findNewTaskList();
        for (Task entity : entities) {
            TaskMessage message = TaskMessage.createSend(DeviceFunctionEnum.getEnumByType(entity.getFunctionCommand()),
                    DeviceDataEnum.getEnumByType(entity.getDataCommand().shortValue()),
                    entity.getDevicePointCode().shortValue(),
                    entity.getTaskId());

            if ((System.currentTimeMillis() - entity.getCreateTime().getTime()) > 3000) {
                log.info("execute command：{}", JSON.toJSONString(message));
                deviceServer.send(entity.getDeviceCode(), message);
            }
        }
    }

}
